<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :rules="queryRules"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="模板名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="考核年度" prop="year">
                <el-input
                    v-model="queryParams.year"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['hrm:model:add']"
                        >新增</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="modelList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="index" label="序号" />
                <el-table-column
                    label="考核模板名称"
                    align="center"
                    prop="name"
                />
                <el-table-column
                    label="考核指标名称"
                    align="center"
                    prop="items"
                >
                    <template slot-scope="scope">
                        <div
                            v-if="
                                $store.getters.allDefectObj['HR-WEB-141'] == 1
                            "
                        >
                            <div
                                v-show="tag.name"
                                v-for="tag in scope.row.items"
                                :key="tag.id"
                                style="margin-left: 10px"
                                closable
                                @close="handleDeleteItem(tag.id)"
                            >
                                {{ tag ? tag.name : "" }}
                            </div>
                        </div>
                        <div v-else>
                            {{
                                scope.row.items &&
                                scope.row.items[0] &&
                                scope.row.items[0].name
                                    ? scope.row.items[0].name
                                    : ""
                            }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="考核年度" align="center" prop="year" />
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleAddItem(scope.row)"
                            v-hasPermi="['hrm:model:edit']"
                            >添加考核指标</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['hrm:model:edit']"
                            >修改</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['hrm:model:remove']"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改考核模型对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-form-item label="考核模板名称" prop="name">
                        <el-input
                            v-model="form.name"
                            placeholder="请输入考核模板名称"
                        />
                    </el-form-item>
                    <el-form-item label="考核指标" prop="itemIds">
                        <el-select
                            v-if="
                                this.$store.getters.allDefectObj[
                                    'HR-WEB-142'
                                ] == 0 && !form.id
                            "
                            @change="changeItem($event)"
                            v-model="form.itemId"
                            placeholder="请选择考核指标"
                        >
                            <el-option>
                                v-for="item in itemList" :key="item.id"
                                :label="item.name" :value="item.id" ></el-option
                            >
                        </el-select>
                        <el-select
                            v-else
                            multiple
                            v-model="form.itemIds"
                            placeholder="请选择考核指标"
                        >
                            <el-option
                                v-for="item in itemList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="考核年度"
                        prop="year"
                        :rules="
                            $store.getters.allDefectObj['HR-WEB-143'] == 0 &&
                            !form.id
                                ? [
                                      {
                                          required: true,
                                          message: '考核年度不能为空',
                                          trigger: 'blur',
                                      },
                                      //限制为四位数字
                                      {
                                          pattern: /^\d+$/,
                                          message: '请输入纯数字',
                                          trigger: 'blur',
                                      },
                                  ]
                                : [
                                      {
                                          required: true,
                                          message: '考核年度不能为空',
                                          trigger: 'blur',
                                      },
                                      //限制为四位数字
                                      {
                                          pattern: /^\d{4}$/,
                                          message: '请输入四位数字',
                                          trigger: 'blur',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            v-model="form.year"
                            placeholder="请输入考核年度"
                        />
                    </el-form-item>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">提 交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加考核指标对话框 -->
        <el-dialog
            title="添加考核指标"
            :visible.sync="addOpen"
            width="500px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-form-item label="选择考核指标" prop="name">
                        <el-select
                            multiple
                            v-model="itemIds"
                            placeholder="请选择考核指标"
                        >
                            <el-option
                                v-for="item in itemList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitItem">提 交</el-button>
                <el-button @click="cancelItem">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listModel,
    getModel,
    delModel,
    addModel,
    updateModel,
    addRelation,
    delRelation,
} from "@/api/hrm/model";

import { listItem } from "@/api/hrm/item";

export default {
    name: "Model",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 考核模型表格数据
            modelList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                isAsc: "descending",
                name: null,
                year: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            queryRules: {
                year: [
                    //限制为四位数字
                    {
                        pattern: /^\d{4}$/,
                        message: "请输入四位数字",
                        trigger: "blur",
                    },
                ],
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "考核模板名称不能为空",
                        trigger: "blur",
                    },
                ],
                itemIds: [
                    {
                        required: true,
                        message: "考核指标不能为空",
                        trigger: "chagne",
                    },
                ],
                year: [],
            },
            itemList: [],
            itemIds: [],
            modelId: null,
            addOpen: false,
        };
    },
    created() {
        this.getList();
        this.getListItem();
    },
    methods: {
        changeItem(id) {
            this.form.itemIds = [];
            this.form.itemIds.push(id);
        },
        handleDeleteItem(id) {
            delRelation(id).then((response) => {
                this.$modal.msgSuccess("删除指标");
                this.getList();
            });
        },
        getListItem() {
            listItem({ pageNum: 1000 }).then((response) => {
                this.itemList = response.rows;
            });
        },

        /** 查询考核模型列表 */
        getList() {
            this.loading = true;
            listModel(this.queryParams).then((response) => {
                this.modelList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        cancelItem() {
            this.addOpen = false;
            this.resetItemForm();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                year: null,
                createTime: null,
                createBy: null,
                updateBy: null,
                updateTime: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    this.queryParams.pageNum = 1;
                    this.getList();
                }
            });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增加模版";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getModel(id).then((response) => {
                this.form = response.data;
                this.form.itemIds = [];
                for (let item in response.data.items) {
                    this.form.itemIds.push(response.data.items[item].id);
                }

                this.open = true;
                this.title = "修改模版";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateModel(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addModel(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        resetItemForm() {
            this.itemIds = [];
        },
        handleAddItem(row) {
            this.resetItemForm();
            this.modelId = row.id;
            this.itemIds = [];
            if (row.items && row.items.length > 0) {
                row.items.forEach((element) => {
                    if (element.id) {
                        this.itemIds.push(Number(element.id));
                    }
                });
            }
            this.addOpen = true;
        },

        /** 提交按钮 */
        submitItem() {
            if (this.itemIds.length > 0) {
                addRelation({
                    modelId: this.modelId,
                    itemIds: this.itemIds,
                }).then((response) => {
                    this.$modal.msgSuccess("添加指标成功");
                    this.addOpen = false;
                    this.getList();
                });
            } else {
                this.$modal.msgError("请选择指标");
            }
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm(
                    "模版删除后不可恢复，且有关联业务发生的模版，不能删除。确认删除？"
                )
                .then(function () {
                    return delModel(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("已经完成删除！");
                })
                .catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "hrm/model/export",
                {
                    ...this.queryParams,
                },
                `model_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
